<template>
  <div class="header-container">
    <div class="header-left">
      <div class="logo-section">
        <i class="el-icon-s-platform logo-icon"></i>
        <span class="logo-text">Rain Admin</span>
      </div>
    </div>

    <div class="header-right">
      <div class="user-info" v-if="user.token != ''">
        <div class="user-details">
          <div class="welcome-text">
            欢迎回来！{{ user.name }}
          </div>
          <div class="user-role">
            <i class="el-icon-user"></i>
            管理员
          </div>
        </div>

        <div class="headImg">
          <img
            :src="user.headImg || require('@/assets/no_image.jpg')"
            :alt="user.name"
            @mouseover="showLogout"
            @mouseout="hideLogout"
            @focus="showLogout"
            @blur="hideLogout"
            tabindex="0"
          />

          <!-- 退出按钮 -->
          <button
            class="logoutButton"
            @click="logout"
            @mouseover="showLogout"
            @mouseout="hideLogout"
            @focus="showLogout"
            @blur="hideLogout"
          >
            退出
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import SessionStorage from '../../public/static/js/session-storage'
import useTool from '../../public/static/js/tool'

export default {
  name: 'HeadView',
  data () {
    return {
      user: {
        token: '',
        name: '',
        headImg: require('@/assets/no_image.jpg')
      }
    }
  },
  mounted () {
    this.checkUserLogin()
  },
  methods: {
    checkUserLogin () {
      const { getLoginAdmin } = useTool()
      const token = getLoginAdmin()
      // 如果没有登录 token，则设置默认头像并退出
      if (useTool().isEmpty(token)) {
        this.user.token = ''
        this.user.headImg = require('@/assets/no_image.jpg')
        this.$emit('update-user', this.user)
        return
      }
      this.user.token = token // 设置token
      // 发起请求获取用户信息
      this.$ajax.post('/admin/user/token', { token: token })
        .then((response) => {
          if (response.data) {
            const resp = response.data
            if (resp.code === 0) {
              this.user = {
                ...resp.data,
                headImg: resp.data.headImg || require('@/assets/no_image.jpg')
              }
              if (resp.data.headImg) {
                this.showVie() // 获取头像
              } else {
                // 如果获取的用户信息没有headImg，也emit一次默认头像的用户数据
                this.$emit('update-user', this.user)
              }
            } else {
              this.$message.error(resp.msg || '获取用户信息失败')
              this.user.headImg = require('@/assets/no_image.jpg')
            }
            // 在成功或失败后都 emit 用户数据
            this.$emit('update-user', this.user)
          }
        })
        .catch((error) => {
          console.error('Request failed:', error)
          this.user.headImg = require('@/assets/no_image.jpg')
          // 请求失败也 emit 用户数据
          this.$emit('update-user', this.user)
        })
    },
    showVie () {
      const filename = this.user.headImg
      // 如果已经加载过这个头像，直接返回
      if (this.user.headImg && this.user.headImg.startsWith('data:image')) {
        console.log('使用缓存的头像数据')
        this.$emit('update-user', this.user)
        return
      }
      console.log('开始获取头像，文件名：', filename)
      if (!filename || filename.trim() === '') {
        console.log('头像文件名为空，使用默认头像')
        this.user.headImg = require('@/assets/no_image.jpg')
        this.$emit('update-user', this.user)
        return
      }
      const url = `/photo/view?filename=${filename}`
      console.log('请求头像URL：', url)
      this.$ajax.get(url, {
        responseType: 'blob',
        headers: {
          Authorization: this.user.token
        }
      })
        .then((response) => {
          console.log('获取头像响应类型：', response.data.type)
          console.log('获取头像响应大小：', response.data.size)
          if (response.data.size === 0) {
            console.error('头像数据为空')
            throw new Error('Empty image data')
          }
          // 压缩图片
          this.compressImage(response.data)
        })
        .catch((error) => {
          console.error('获取头像失败：', error)
          this.user.headImg = require('@/assets/no_image.jpg')
          this.$emit('update-user', this.user)
        })
    },
    compressImage (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const img = new Image()
        img.onload = () => {
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')

          // 设置最大尺寸
          const MAX_WIDTH = 200
          const MAX_HEIGHT = 200
          let width = img.width
          let height = img.height

          if (width > height) {
            if (width > MAX_WIDTH) {
              height *= MAX_WIDTH / width
              width = MAX_WIDTH
            }
          } else {
            if (height > MAX_HEIGHT) {
              width *= MAX_HEIGHT / height
              height = MAX_HEIGHT
            }
          }

          canvas.width = width
          canvas.height = height
          ctx.drawImage(img, 0, 0, width, height)

          // 转换为较小的 JPEG
          const compressedDataUrl = canvas.toDataURL('image/jpeg', 0.7)
          console.log('压缩后的图片大小：', Math.round(compressedDataUrl.length * 0.75), 'bytes')
          this.user.headImg = compressedDataUrl
          this.$emit('update-user', this.user) // 压缩后emit
          this.$forceUpdate()
        }
        img.src = e.target.result
      }
      reader.readAsDataURL(file)
    },
    showLogout () {
      const logoutBtn = document.querySelector('.logoutButton')
      if (logoutBtn) logoutBtn.classList.add('show')
    },
    hideLogout () {
      const logoutBtn = document.querySelector('.logoutButton')
      if (logoutBtn) logoutBtn.classList.remove('show')
    },
    logout () {
      this.$confirm('确定退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 先调用后端登出接口
          this.$ajax.post('/admin/user/logout')
            .then((response) => {
              const resp = response.data
              if (resp.code === 0) {
                // 后端登出成功后，再清除本地存储
                const { remove } = SessionStorage()
                remove('SESSION_KEY_LOGIN_ADMIN')

                // 更新组件的用户状态
                this.user = {
                  token: '',
                  name: '',
                  headImg: require('@/assets/no_image.jpg')
                }
                this.$emit('update-user', this.user)

                this.$message.success(resp.msg)
                // 使用 nextTick 确保状态更新后再跳转
                this.$nextTick(() => {
                  this.$router.push('/login')
                })
              } else {
                this.$message.error(resp.msg || '退出登录失败')
              }
            })
            .catch((error) => {
              console.error('退出登录请求失败:', error)
              this.$message.error('退出登录失败，请重试')
            })
        })
        .catch(() => {
          console.log('用户取消了退出操作')
        })
    },
    handleImageError (e) {
      console.error('图片加载失败：', e)
      this.user.headImg = require('@/assets/no_image.jpg')
      this.$emit('update-user', this.user) // 图片加载失败也emit
    },
    handleImageLoad (e) {
      console.log('图片加载成功：', e)
      // 图片加载成功后，如果需要，可以在这里emit更新（通常在showVie或compressImage里emit足够）
    }
  }
}
</script>

<style scoped>
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  color: white;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.logo-icon {
  font-size: 24px;
  color: #fff;
}

.logo-text {
  font-size: 18px;
  font-weight: bold;
  color: #fff;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 25px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.welcome-text {
  font-size: 14px;
  font-weight: 500;
  color: #fff;
}

.user-role {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

.user-role i {
  font-size: 10px;
}

.headImg {
  position: relative;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.headImg img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.3s ease;
  cursor: pointer;
}

.headImg:hover {
  border-color: rgba(255, 255, 255, 0.6);
  transform: scale(1.05);
}

.logoutButton {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  border: none;
  border-radius: 50%;
  display: none;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 1000;
  font-size: 14px;
  padding: 0;
}

.logoutButton:hover {
  background-color: rgba(0, 0, 0, 0.7);
}

.logoutButton.show {
  display: flex;
}

.logoutButton:focus {
  outline: none;
}

.headImg img:focus {
  outline: 2px solid #409EFF;
  outline-offset: 2px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-container {
    padding: 0 10px;
  }

  .logo-text {
    display: none;
  }

  .user-details {
    display: none;
  }
}
</style>
